package com.dormitory.management.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory.management.system.entity.Building;
import com.dormitory.management.system.entity.Living;
import com.dormitory.management.system.req.LivingSaveReq;
import com.dormitory.management.system.mapper.LivingMapper;
import com.dormitory.management.system.req.LivingPageReq;
import com.dormitory.management.system.req.LivingUpdateReq;
import com.dormitory.management.system.service.BuildingService;
import com.dormitory.management.system.service.LivingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.management.system.service.RoomService;
import com.dormitory.managemnet.util.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 生活区表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class LivingServiceImpl extends ServiceImpl<LivingMapper, Living> implements LivingService {

    @Autowired
    private BuildingService buildingService;
    @Autowired
    private RoomService roomService;

    @Override
    public boolean save(LivingSaveReq req) {
        return this.baseMapper.insert(BeanUtil.copyProperties(req,Living.class))>0;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        List<Building> list = buildingService.list(new QueryWrapper<Building>().lambda().eq(Building::getLivingId, id));
        if (!list.isEmpty()) {
            for (Building building : list) {
                //删除对应楼栋
                buildingService.delete(building.getId());
            }
        }
        //删除对应生活区
        return this.baseMapper.deleteById(id)>0;
    }

    @Override
    public boolean update(LivingUpdateReq req) {
        return this.baseMapper.updateById(BeanUtil.copyProperties(req,Living.class))>0;
    }

    @Override
    public IPage<Living> getPage(LivingPageReq req) {
        Page<Living> page = new Page<>(req.getPageCurrent(),req.getPageSize());
        LambdaQueryWrapper<Living> lambda = new QueryWrapper<Living>().lambda()
                .eq(req.getId()!=null,Living::getId,req.getId())
                .like(req.getAddress()!=null,Living::getAddress,req.getAddress());
        return this.baseMapper.selectPage(page, lambda);
    }

}
